package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizeCodeEnum;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 集中处理所有异常
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.atguigu.gulimall.product.app")
public class GulimallExceptionControllerAdvice {

    /**
     * 数据校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{}，异常类型{}",e.getMessage().getClass());

        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> errMap = new HashMap<>();

        bindingResult.getFieldErrors().forEach((item)->{
            errMap.put(item.getField(), item.getDefaultMessage());
        });

        return R.error(BizeCodeEnum.VAILD_EXCEPTION.getCode(), BizeCodeEnum.VAILD_EXCEPTION.getMessage()).put("data",errMap);

    }

    /**
     * 统一异常
     * @param throwable
     * @return
     */
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable){

        throwable.printStackTrace();
        log.error(throwable.toString());

        return R.error(BizeCodeEnum.UNKNOW_EXCEPTION.getCode(), BizeCodeEnum.UNKNOW_EXCEPTION.getMessage());

    }
}
